package com.sinvo.oa.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sinvo.oa.entity.model.wechat.Menu;
import com.sinvo.oa.entity.vo.wechat.MenuVo;
import com.sinvo.oa.exception.CustomException;
import com.sinvo.oa.mapper.WechatMenuMapper;
import com.sinvo.oa.result.ResultCode;
import com.sinvo.oa.service.WechatMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description WechatMenuService实现类
 */
@Service
public class WechatMenuServiceImpl extends ServiceImpl<WechatMenuMapper, Menu> implements WechatMenuService {

    @Autowired
    private WxMpService wxMpService;

    @Override
    public List<MenuVo> findMenuInfo() {
        //获取所有菜单
        List<Menu> menuList = this.list();
        List<Menu> firstMenuList = menuList.stream().filter(item -> item.getParentId() == 0)
                .collect(Collectors.toList());
        List<MenuVo> voList = new ArrayList<>();
        for (Menu firstMenu : firstMenuList) {
            //menu->menuVo
            MenuVo firstMenuVo = new MenuVo();
            BeanUtils.copyProperties(firstMenu,firstMenuVo);
            List<Menu> secondMenuList = menuList.stream().filter(item -> item.getParentId() == firstMenu.getId())
                    .collect(Collectors.toList());
            //List<Menu> -> List<MenuVo>
            List<MenuVo> children = new ArrayList<>();
            for (Menu secondMenu : secondMenuList) {
                MenuVo secondMenuVo = new MenuVo();
                BeanUtils.copyProperties(secondMenu,secondMenuVo);
                children.add(secondMenuVo);
            }
            firstMenuVo.setChildren(children);
            voList.add(firstMenuVo);
        }
        System.out.println("voList:"+voList);
        return voList;
    }

    @Override
    public void sync() {
        List<MenuVo> menuVoList = this.findMenuInfo();
        //菜单
        JSONArray buttonList = new JSONArray();
        for(MenuVo firstMenuVo : menuVoList) {
            JSONObject one = new JSONObject();
            one.put("name", firstMenuVo.getName());
            if(CollectionUtils.isEmpty(firstMenuVo.getChildren())) {
                one.put("type", firstMenuVo.getType());
                one.put("url", "http://22b4c373.r8.cpolar.top/#"+firstMenuVo.getUrl());
            } else {
                JSONArray subButton = new JSONArray();
                for(MenuVo secondMenuVo : firstMenuVo.getChildren()) {
                    JSONObject view = new JSONObject();
                    view.put("type", secondMenuVo.getType());
                    if(secondMenuVo.getType().equals("view")) {
                        view.put("name", secondMenuVo.getName());
                        //H5页面地址
                        view.put("url", "http://22b4c373.r8.cpolar.top/#"+secondMenuVo.getUrl());
                    } else {
                        view.put("name", secondMenuVo.getName());
                        view.put("key", secondMenuVo.getMenuKey());
                    }
                    subButton.add(view);
                }
                one.put("sub_button", subButton);
            }
            buttonList.add(one);
        }
        //菜单
        JSONObject button = new JSONObject();
        button.put("button", buttonList);
        System.out.println("buttonList:"+buttonList);
        //菜单推送
        try {
            wxMpService.getMenuService().menuCreate(button.toJSONString());
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void removeMenu() {
        try {
            wxMpService.getMenuService().menuDelete();
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveMenu(Menu menu) {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getName,menu.getName());
        int count = this.count(queryWrapper);
        if (count > 0){
            throw new CustomException(ResultCode.DATA_ERROR.getCode(), "菜单名重复");
        }
        boolean success = this.save(menu);
        if (!success){
            throw new CustomException(ResultCode.SERVICE_ERROR.getCode(), "保存失败，请重试");
        }
    }

    @Override
    public void updateMenu(Menu menu) {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getName,menu.getName());
        Menu one = this.getOne(queryWrapper);
        if (one != null && one.getId() != menu.getId()){
            throw new CustomException(ResultCode.DATA_ERROR.getCode(), "菜单名重复");
        }
        boolean success = this.updateById(menu);
        if (!success){
            throw new CustomException(ResultCode.SERVICE_ERROR.getCode(), "保存失败，请重试");
        }
    }
}
